<template>


  <div @submit="handleSubmit">
    <a-form :form="form">

      <!--companyId-->

      <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="所属公司">
        <a-select
          @change="handleProvinceChange"
          v-decorator="[ 'companyId', {rules: [{ required: true, message: '请选择所属公司' }],initialValue: defaultCompany}]"
          placeholder="请选择所属公司">
          <a-select-option :value="company.id" v-for="company in companyList" :key="company.id">
            {{company.name}}
          </a-select-option>
        </a-select>
      </a-form-item>


      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="批次号">
        <a-input placeholder="批次号"
                 v-decorator="[ 'couponStockId', {rules: [{ required: true, message: '请输入批次号' }]}]"
        ></a-input>
      </a-form-item>


      <!--merchantId 下拉可多选商户 -->

      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="适用商户">
        <a-select mode="multiple" placeholder="请选择适用商户"
                  v-decorator="[ 'merchantIds', {rules: [{ required: true, message: '请选择适用商户' }]}]">
          <a-select-option v-for="merchant in merchantList" :key="merchant.id">{{merchant.name}}
          </a-select-option>
        </a-select>
      </a-form-item>


      <a-form-item
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        label="优惠券图"
      >
        <a-upload
          :action="this.$baseURL+'/pc/common/uploadImg'"
          listType="picture-card"
          :fileList="fileList"
          @preview="uploadPreview"
          @change="uploadChange"
        >
          <div v-if="fileList.length < 1">
            <a-icon type="plus"/>
            <div class="ant-upload-text">上传优惠券图</div>
          </div>
        </a-upload>
        <a-modal :visible="previewVisible" :footer="null" @cancel="uploadCancel">
          <img alt="example" style="width: 100%" :src="previewImage"/>
        </a-modal>
      </a-form-item>

      <!--note 简介描述 -->
      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="简介描述">

        <!--v-model="content"-->
        <quill-editor
          v-model="content"
          ref="myQuillEditor"
          :options="editorOption"
          @blur="onEditorBlur($event)" @focus="onEditorFocus($event)"
          @change="onEditorChange($event)">
        </quill-editor>

      </a-form-item>


      <a-form-item
        v-bind="buttonCol"
      >
        <a-row>
          <a-col span="6">
            <a-button type="primary" html-type="submit">提交</a-button>
          </a-col>
          <a-col span="10">
            <a-button @click="handleGoBack">返回</a-button>
          </a-col>
          <a-col span="8"></a-col>
        </a-row>
      </a-form-item>

    </a-form>
  </div>

</template>

<script>
  import { save } from '../../../api/business/product'
  import { selectAllMerchant } from '../../../api/business/merchant'
  import { selectAllCompany } from '../../../api/system/company'
  import pick from 'lodash.pick'


  import { quillEditor } from 'vue-quill-editor'
  import 'quill/dist/quill.core.css'
  import 'quill/dist/quill.snow.css'
  import 'quill/dist/quill.bubble.css'

  export default {
    components: {
      quillEditor
    },
    props: {},
    //--############  data() ###############-->
    data() {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        buttonCol: {
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 12, offset: 5 }
          }
        },
        visible: false,
        confirmLoading: false,
        mdl: {},
        form: this.$form.createForm(this),
        isDisabled: false,

        companyList: [],
        merchantList: [],
        id: 0,

        //设置默认公司
        defaultCompany: '',

        //图片上传
        fileList: [],
        previewVisible: false,
        previewImage: '',

        editorOption: {
          modules: {
            toolbar: [
              ['bold', 'italic', 'underline', 'strike', 'clean'],
              ['blockquote', 'code-block'],
              [{ 'list': 'ordered' }, { 'list': 'bullet' }],
              [{ 'script': 'sub' }, { 'script': 'super' }],
              [{ 'indent': '-1' }, { 'indent': '+1' }],
              [{ 'direction': 'rtl' }],
              [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
              [{ 'color': [] }, { 'background': [] }]
            ]
          }
        },
        content: ''
      }
    },
    //--############  data() ###############-->

    created() {
      this.getAllCompany()

      // this.getAllMerchant()
    },
    mounted() {

    },
    //--############  methods() ###############-->
    methods: {
      handleGoBack() {
        this.$emit('onGoBack')
      },
      //公司改变
      handleProvinceChange(value) {
        console.log(value);
        // this.merchantIds=[];
        if(value){
          this.getAllMerchant(value)
        }

      },
      onEditorBlur() {
      }, // 失去焦点事件
      onEditorFocus() {
      }, // 获得焦点事件
      onEditorChange() {
      }, // 内容改变事件
      // 转码
      escapeStringHTML(str) {
        str = str.replace(/&lt;/g, '<')
        str = str.replace(/&gt;/g, '>')
        return str
      },
      uploadCancel() {
        this.previewVisible = false
      },
      uploadPreview(file) {
        this.previewImage = file.url || file.thumbUrl
        this.previewVisible = true
      },
      uploadChange(info) {
        //console.log(info)
        this.fileList = info.fileList
        if (info.file.status === 'done') {
          this.fileList.pop()
          this.fileList.push(info.file)
          this.$message.success(`${info.file.name} 上传成功`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败`)
        } else if (info.file.status === 'removed') {
          deletePic(info.file.uid).then(res => {

          })
        }
      },


      getAllCompany: function() {
        selectAllCompany().then(res => {
          if (res.code === 200) {
            this.companyList = res.result
            this.defaultCompany = this.companyList[0].id
            this.getAllMerchant(this.defaultCompany);
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      getAllMerchant: function(companyId) {
        console.log("add"+companyId);
        selectAllMerchant(companyId).then(res => {
          if (res.code === 200) {
            this.merchantList = res.result
          } else {
            this.$notification.error({
              message: '错误',
              description: res.message,
              duration: 4
            })
          }
        })
      },
      handleSubmit() {
        const _this = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          // 验证表单没错误
          if (!err) {
            values.id = this.mdl.id
            _this.confirmLoading = true
            // 模拟后端请求 2000 毫秒延迟

            if (_this.content == '') {
              this.$notification.warning({
                message: '警告',
                description: '请先填写优惠券简介描述',
                duration: 4
              })
            } else if (_this.fileList == '') {
              this.$notification.warning({
                message: '警告',
                description: '请先上传优惠券图片',
                duration: 4
              })
            } else {
              values.note = _this.content
              let packageFileList1 = packageFileList(this.fileList)
              values.fileList = packageFileList1
              // values.fileList = _this.fileList
              console.log(values)
              save(values).then((res) => {
                if (res.code === 200) {
                  _this.$message.success('添加成功')
                  this.$emit('onGoBack')
                } else {
                  this.$notification.error({
                    message: '错误',
                    description: res.message,
                    duration: 4
                  })
                }
              }).catch(() => {
                // Do something
              }).finally(() => {
                _this.confirmLoading = false
              })
            }
          }
        })

      }

    }
    //--############  methods() ###############-->
  }

  function packageFileList(fileList) {
    let fileLists = []
    for (let i = 0; i < fileList.length; i++) {
      fileLists.push(fileList[i].response)
    }
    return fileLists
  }
</script>

<style>
  .ql-container {
    height: 300px;
  }
</style>
